import * as _ from "lodash"
import httpClient from "../httpclient"
import { CarrierCode } from "./carrier"


export enum TrackingStatus {
  Unknown = "unknown", // 未知
  PreTransit = "pre_transit", // 等待拦包
  InTransit = "in_transit", //运输中
  Delivered = "delivered", //已送达
  Returned = "returned", //退回
  Failure = "failure" // 异常
}

export class TrackingEvent {
  public status: TrackingStatus
  public message: string
  private occurred_time: string

  public get occurredTime() {
    return this.occurred_time
  }

  public set occurredTime(occurredTime) {
    this.occurred_time = occurredTime
  }

}

export class Track {

  private carrier_code: CarrierCode
  private tracking_number: string
  private tracking_status: TrackingStatus
  private shipped_time: string
  public events: TrackingEvent[]

  public get carrierCode() {
    return this.carrier_code
  }

  public set carrierCode(code) {
    this.carrier_code = code
  }

  public get trackingNumber() {
    return this.tracking_number
  }

  public set trackingNumber(trackingNumber) {
    this.tracking_number = trackingNumber
  }

  public get trackingStatus() {
    return this.tracking_status
  }

  public set trackingStatus(status) {
    this.tracking_status = status
  }

  public get shippedTime() {
    return this.shipped_time
  }

  public set shippedTime(shippedTime) {
    this.shipped_time = shippedTime
  }


  public static assign(tracker: Track): Track {
    if (_.isUndefined(tracker)) {
      return new Track()
    }
    return _.assign(new Track(), tracker, {
      events: _.map(tracker.events, event => _.assign(new TrackingEvent(), event)),
    })
  }
}

export class TrackingService {
  public static getTrack(code: CarrierCode, trackingNumber: string): Promise<Track> {
    return httpClient.get(`/v1/carriers/${code}/tracks/${trackingNumber}`)
      .then(({ data }) => data)
      .then(Track.assign)
  }
}
